package com.zidian.teacher.activity;

import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatEditText;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;
import com.zidian.teacher.R;
import com.zidian.teacher.bean.StudentDetailBean;
import com.zidian.teacher.common.Constant;
import com.zidian.teacher.utils.GetUserInfo;
import com.zidian.teacher.utils.ProgressBarBlackUtil;
import com.zidian.teacher.utils.ToastUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.Call;

/**
 * Created by Administrator on 2016/9/8 0008.
 * 学生的详情
 */
public class StudentDetailActivity extends AppCompatActivity {

    @Bind(R.id.study_image)
    CircleImageView studyImage;
    @Bind(R.id.study_name)
    TextView studyName;
    @Bind(R.id.study_class)
    TextView studyClass;
    @Bind(R.id.study_evaluate)
    TextView studyEvaluate;
    @Bind(R.id.read_num)
    TextView readNum;
    @Bind(R.id.student_id)
    TextView studentIdText;
    @Bind(R.id.student_class_scores)
    TextView studentClassScores;
    @Bind(R.id.student_innovate_scores)
    TextView studentInnovateScores;
    @Bind(R.id.class_scores_btn)
    Button classScoresBtn;
    @Bind(R.id.toolbar_back)
    ImageButton toolbarBack;

    private String courseId = "";
    private String studentId = "";
    private String gradeId = "";
    private String studentName = "";
    private float classroomGradeBefore;
    private float innovateGradeBefore;
    private PopupWindow popupWindow;
    //课堂加分
    private static final int ADD_CLASS_SCORE = 1;
    //创新加分
    private static final int ADD_INNOVATE_SCORE = 2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_student_detail);
        ButterKnife.bind(this);
        courseId = getIntent().getStringExtra("courseId");
        studentId = getIntent().getStringExtra("studentId");
        studentName = getIntent().getStringExtra("studentName");
        initView();
        getStudentDetail();
    }

    private void initView() {
        toolbarBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    /**
     * 修改学生创新加分
     */
    @OnClick(R.id.innovate_scores_btn)
    void addInnovateScore() {
        showPopupWindow(ADD_INNOVATE_SCORE);
    }

    /**
     * 修改学生课堂加分
     */
    @OnClick(R.id.class_scores_btn)
    void addClassScore() {
        showPopupWindow(ADD_CLASS_SCORE);
    }

    /**
     * 显示加分popupWindow
     */
    private void showPopupWindow(final int type) {
        View view = View.inflate(this, R.layout.popupwindow_add_score, null);
        final TextInputLayout inputScoreHint = (TextInputLayout) view.findViewById(R.id.input_score_hint);
        final AppCompatEditText addScoreEt = (AppCompatEditText) view.findViewById(R.id.add_score_et);
        ImageView sureIv = (ImageView) view.findViewById(R.id.add_score_sure);
        ImageView cancelIv = (ImageView) view.findViewById(R.id.add_score_cancel);
        TextView titleTv = (TextView) view.findViewById(R.id.add_score_title);
        addScoreEt.setInputType(InputType.TYPE_CLASS_NUMBER);
        if (type == ADD_CLASS_SCORE) {
            titleTv.setText("请输入您对" + studentName + "的课堂加分");
        } else if (type == ADD_INNOVATE_SCORE) {
            titleTv.setText("请输入您对" + studentName + "的创新加分");
        }
        cancelIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addScoreEt.setText("");
                popupWindow.dismiss();
            }
        });
        sureIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String score = addScoreEt.getText().toString().trim();
                if (TextUtils.isEmpty(score)) {
                    inputScoreHint.setError("加分不能为空");
                    return;
                }
                if (inputScoreHint.isErrorEnabled()) {
                    inputScoreHint.setErrorEnabled(false);
                }
                //判断是哪种加分
                if (type == ADD_CLASS_SCORE) {
                    studentClassScores.setText(Float.parseFloat(score) + classroomGradeBefore + "");
                    classroomGradeBefore = classroomGradeBefore + Float.parseFloat(score);
                    updateStudentScores(score, "0");
                } else if (type == ADD_INNOVATE_SCORE) {
                    studentInnovateScores.setText(Float.parseFloat(score) + innovateGradeBefore + "");
                    innovateGradeBefore = innovateGradeBefore + Float.parseFloat(score);
                    updateStudentScores("0", score);
                }
                addScoreEt.setText("");
                popupWindow.dismiss();
            }
        });
        popupWindow = new PopupWindow(view, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);
        popupWindow.setFocusable(true);
        popupWindow.showAtLocation(classScoresBtn, Gravity.CENTER, 0, 0);
    }

    /**
     * 网络请求
     * 得到学生详细信息
     */
    private void getStudentDetail() {

        String loginUrl = Constant.URL_GOAL + "grade/selectOne";
        HashMap<String, String> map = new HashMap<>();
        map.put("courseId", courseId);
        map.put("teacherId", GetUserInfo.getTeacherId(this));
        map.put("studentId", studentId);
        map.put("token", GetUserInfo.getToken(this));

        ProgressBarBlackUtil.loadShow(this);
        OkHttpUtils.post().url(loginUrl).params(map).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                ProgressBarBlackUtil.loadCancel();
                ToastUtil.showToast(StudentDetailActivity.this, "获取列表失败！");
            }

            @Override
            public void onResponse(String response, int id) {
                ProgressBarBlackUtil.loadCancel();
                Log.e("T", response);
                try {
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(response);
                    int resultCode = jsonObject.getInt("code");

                    if (resultCode != 200) {
                        ToastUtil.showToast(StudentDetailActivity.this, jsonObject.getString("message"));
                        return;
                    }

                } catch (JSONException e) {

                }

                Gson gson = new Gson();
                StudentDetailBean model = gson.fromJson(response, StudentDetailBean.class);


                if (model.isSuccess()) {

                    Glide.with(StudentDetailActivity.this)
                            .load("")
                            .placeholder(R.drawable.student)
                            .centerCrop()
                            .into((studyImage));
                    //学生名字改为上个界面传过来的值，由于昵称与姓名混淆了
                    studyName.setText(studentName);
                    studentIdText.setText(model.getStudentId());
                    studyEvaluate.setText(model.getCommentNum());
                    readNum.setText(model.getViewedNum());
                    studyClass.setText(model.getStudentClass());
                    studentClassScores.setText(model.getClassroomGrade());
                    studentInnovateScores.setText(model.getInnovateGrade());
                    //得到成绩ID
                    gradeId = model.getGradeId();
                    classroomGradeBefore = Float.parseFloat(model.getClassroomGrade());
                    innovateGradeBefore = Float.parseFloat(model.getInnovateGrade());
                }

            }
        });

    }

    /**
     * 增加学生加分
     *
     * @param classroomGrade 课堂加分
     * @param innovateGrade
     */
    private void updateStudentScores(final String classroomGrade, final String innovateGrade) {
        String loginUrl = Constant.URL_GOAL + "grade/updOne";
        HashMap<String, String> map = new HashMap<>();
        map.put("courseId", courseId);
        map.put("teacherId", GetUserInfo.getTeacherId(this));
        map.put("studentId", studentId);
        if (gradeId == null) {
            gradeId = "0";
        }
        map.put("gradeId", gradeId);
        map.put("classroomGrade", classroomGrade);
        map.put("innovateGrade", innovateGrade);
        map.put("token", GetUserInfo.getToken(this));
        ProgressBarBlackUtil.loadShow(this);
        OkHttpUtils.post().url(loginUrl).params(map).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                ProgressBarBlackUtil.loadCancel();
                Log.e("T", e.toString());
                Snackbar.make(studyImage, "修改成绩失败！", Snackbar.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(String response, int id) {
                ProgressBarBlackUtil.loadCancel();
                Log.e("T", response);
                try {
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(response);
                    int resultCode = jsonObject.getInt("code");

                    if (resultCode != 200) {
                        ToastUtil.showToast(StudentDetailActivity.this, jsonObject.getString("message"));
                        return;
                    } else { //修改成功

                        Snackbar.make(studyImage, "修改成功", Snackbar.LENGTH_SHORT).show();
                    }

                } catch (JSONException e) {

                }
            }
        });


    }
}